package com.maimao.search.controller.base;

import com.maimao.core.enums.ExceptionEnum;
import com.maimao.core.exception.MaiMaoException;
import com.maimao.core.model.auth.AuthUser;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.Oauth2Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author MaoLin Wang
 * @date 2020/12/8 4:40 下午
 */
public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public AuthUser checkAndGetAuthUser(){
        AuthUser authUser = Oauth2Util.getUserFromRequest(getRequest());
        if (authUser==null){
            throw new MaiMaoException(ExceptionEnum.NOT_LOGIN);
        }
        return authUser;
    }

    public Result entityInvalid(BindingResult bindingResult){
        return Result.notValid(bindingResult.getFieldErrors().get(0).getDefaultMessage());
    }
    public HttpSession getSession() {
        return getRequest().getSession();
    }

    public HttpSession getSession(HttpServletRequest request) {
        return request.getSession();
    }

    public String getSessionUrl(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        sb.append(request.getScheme());
        sb.append("://");
        sb.append(request.getServerName());
        sb.append(":");
        sb.append(request.getServerPort());
        sb.append(request.getContextPath());
        return sb.toString();
    }
}
